const Url = require('url');
const moment = require('moment');

const viewPort = {width: 1920, height: 1080};

/**
 * 任务
 */
class Task {
    /**
     *
     * @param url 截图的网址
     * @param sleep init后，截图前等待的时间
     */
    constructor(url, sleep = 0) {
        this.__url = url;
        this.__sleep = sleep;
        this.__init = false;
        this.__hasTimeLayer = false;
        const parse = Url.parse(url);
        this.hostname = parse.hostname.toLowerCase();
    }

    /**
     *
     * @param page
     * @returns {Promise<number>}
     */
    async init(page) {
        await page.setViewport(viewPort);

        try {
            await page.goto(this.__url, {timeout: 20000, waitUntil: 'domcontentloaded'});
            await this.timeLayer(page);
            if (this.__sleep > 0)
                await sleep(this.__sleep);
            this.__init = true;
        } catch (e) {
            console.error('网页打开错误', this.__url, e);
        }
    }

    /**
     * 等待一定时间
     * @param time
     * @returns {Promise<void>}
     */
    sleep(time) {
        return sleep(time);
    }

    /**
     * 给网页添加时间浮动层
     * @param page
     * @returns {Promise<Task>}
     */
    async timeLayer(page) {
        if (this.__hasTimeLayer)
            return Promise.resolve();
        this.__hasTimeLayer = true;
        await page.addStyleTag({
            content: `.live-time-layer{
                padding: 10px;
                font-size: 28px;
                background: rgba(255,255,255,0.9);
                color: #000;
                position:fixed;
                z-index:999;
                bottom:5px;
                left:5px;
            }`
        });
        await page.evaluate(() => {
            function addZero(i) {
                if (i < 10) {
                    i = "0" + i;
                }
                return i;
            }

            const $layer = document.createElement('pre');
            $layer.className = 'live-time-layer';
            document.body.appendChild($layer);
            const now = new Date();
            const year = now.getFullYear();
            const month = addZero(now.getMonth() + 1);
            const day = addZero(now.getDate());
            const hour = addZero(now.getHours());
            const minute = addZero(now.getMinutes());
            const second = addZero(now.getSeconds());
            $layer.innerText = `截图时间：${year}年${month}月${day}日 ${hour}点${minute}分${second}秒`;
        });
        return this;
    }
}

module.exports = Task;

async function sleep(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time);
    });
}